package ve.usb.cohesion.runtime;

import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;



/**
 * Registro y conexión de usuarios. Incluye la página principal de la aplicación.<br>
 */
public class CohesionAction extends Action {
    
    /**
     * The set of argument type classes for the reflected method call.  These
     * are the same for all calls, so calculate them only once.
     */
    protected static Class[] types =
    {
        ActionMapping.class, ActionForm.class, HttpServletRequest.class,
        HttpServletResponse.class
    };
    
    /**
     * Simple dispacther for actions in cohesion.<br>
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @return The Struts name of the following step.
     * @throws java.lang.Exception For untreated exceptions.
     * These exceptions will normally be treated with
     * the default exception action.
     * @return A forward to the following view or action of the application
     */
    public ActionForward execute(ActionMapping mapping, ActionForm  form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String name="";
        if(request.getServletPath().equals("/UsuarioLogin.do") || validateSession(request)){
            //Simplistic dispatcher based on action path
            name = request.getServletPath().replaceAll("^.*/([^/]*)\\.do", "$1");
        }else{  
            name = request.getServletPath().replaceAll("^.*/([^/]*)\\.do", "UsuarioLoginI");
        }
        
        Method method = getClass().getMethod(name, types);
        return (ActionForward)method.invoke(this, new Object[] {mapping, form, request, response});    
        
        
    }
    
    public void addError(HttpServletRequest request, String msg, String... args) {
        ActionMessages err = getErrors(request);
        if (args.length>0) {
            err.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(msg,args[0]));
        } else err.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(msg));
        addErrors(request, err);
    }
     public boolean validateSession(HttpServletRequest request){
        Boolean conectado =(Boolean)request.getSession().getAttribute("login");
        if(conectado!=null){
            return conectado;
        } else {
            return false;
        }
     }
}